/*****************************************************
** Author: 
** Date: 2019-12-04
*
*****************************************************/

#include <stdlib.h>
#include <time.h>
#include "comm.h"


#define ARRAY_SIZE_MAX		1000
#define ARRAY_SIZE_MIN		100

/**
 * @brief
 * @param  None
 * @retval None
 */
static void sort(unsigned char *buff, int size)
{
	if (size <= 1) {
		log_wrn("size %d err", size);
		return ;
	}

	int i, j;
	unsigned char key;

	for (j = 1; j < size; ++j) {
		key = buff[j];
		i = j - 1;
		// log_dbg("key = buff[%d] = 0x%x buff[%d] 0x%x", j, key, i, buff[i]);

		while (i >= 0 && buff[i] > key) {
			buff[i + 1] = buff[i];
			// log_dbg("buff[%d] 0x%x", i + 1, buff[i + 1]);
			i--;
		}

		// log_dbg("i %d j %d", i, j);
		buff[i + 1] = key;

		// dump_memory(buff, size, "buff during sort");
	}
}

void a2_1(void)
{
	srand(time(NULL));

	int arr_size = rand() % (ARRAY_SIZE_MAX - ARRAY_SIZE_MIN) + ARRAY_SIZE_MIN;
	log_inf("arr_size %d", arr_size);

	unsigned char *buff = malloc(arr_size);
	if (buff == NULL) {
		log_err("malloc buff size %d err", arr_size);
		return ;
	}

	int i;

	for (i = 0; i < arr_size; ++i) {
		buff[i] = (unsigned char)(rand() & 0xff);
	}

	dump_memory(buff, arr_size, "buff init");

	sort(buff, arr_size);

	dump_memory(buff, arr_size, "buff after sort");

	free(buff);
}

/* End of file */



